#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<linux/stat.h>

#define PUBLIC_FIFO "PUBFIFO"
#define PRIVATE1_FIFO "PRIFIFO1"
#define PRIVATE2_FIFO "PRIFIFO2"
#define PRIVATE1_HEADER "Client1's message:"
#define PRIVATE2_HEADER "Client2's message:"
#define SERVER_REPLY "Send message successfully,"

int main()
{
	int pubfd;
	int prifd1;
	int prifd2;
	char str1[40] = "Client1 loading successfully.";
	char str2[40] = "Client2 loading successfully.";
	char readbuf[80] = "";
	umask(0);
	mknod(PUBLIC_FIFO,S_IFIFO|0666,0);
	mknod(PRIVATE1_FIFO,S_IFIFO|0666,0);
	mknod(PRIVATE2_FIFO,S_IFIFO|0666,0);

	prifd1=open(PRIVATE1_FIFO,O_CREAT|O_WRONLY);
	prifd2=open(PRIVATE2_FIFO,O_CREAT|O_WRONLY);

	write(prifd1,str1,strlen(str1));
	write(prifd2,str2,strlen(str2));

	close(prifd1);
	close(prifd2);

	printf("Write data to client.\n");

	while(1)
	{
		memset(readbuf,0,80);
		if((pubfd = open(PUBLIC_FIFO,O_RDWR))==-1)
		{
			printf("Open fifo failed.\n");
			exit(1);
		}
		if(read(pubfd,readbuf,80)!=-1)
		{
			printf("Received string:%s\n",readbuf);
			close(pubfd);
		}
		if(strncmp(readbuf,PRIVATE1_HEADER,strlen(PRIVATE1_HEADER))==0)
		{
			if(((prifd1=open(PRIVATE1_FIFO,O_WRONLY))!=-1)&&((prifd2=open(PRIVATE2_FIFO,O_WRONLY))!=-1))
			{
				// printf("readbuf is : %s\n", readbuf);
				if(write(prifd1,SERVER_REPLY,strlen(SERVER_REPLY))<=0)
				{
					printf("Fail to write.\n");
					exit(1);
				}
				if(write(prifd1,readbuf,strlen(readbuf))<=0)
				{
					printf("Fail to write.\n");
					exit(1);
				}
				close(prifd1);

				if(write(prifd2,readbuf,strlen(readbuf))<=0)
				{
					printf("Fail to write.\n");
					exit(1);
				}
				close(prifd2);
			}
			
		}
		
		if(strncmp(readbuf,PRIVATE2_HEADER,strlen(PRIVATE2_HEADER))==0)
		{
			if(((prifd1=open(PRIVATE1_FIFO,O_WRONLY))!=-1)&&((prifd2=open(PRIVATE2_FIFO,O_WRONLY))!=-1))
			{
				// printf("readbuf is : %s\n", readbuf);
				if(write(prifd2,SERVER_REPLY,strlen(SERVER_REPLY))<=0)
				{
					printf("Fail to write.\n");
					exit(1);
				}
				if(write(prifd1,readbuf,strlen(readbuf))<=0)
				{
					printf("Fail to write.\n");
					exit(1);
				}
				close(prifd1);

				if(write(prifd2,readbuf,strlen(readbuf))<=0)
				{
					printf("Fail to write.\n");
					exit(1);
				}
				close(prifd2);

			}
			
			
		}

	}
	return 0;

}
